package com.aiwhose.aiwhosesystem.aop;

import com.aiwhose.aiwhosecore.bean.system.ApiLogs;
import com.aiwhose.aiwhosesystem.service.ApiLogsService;
import jakarta.annotation.Resource;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.MessageListener;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.context.annotation.Configuration;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

@Configuration
public class SystemMQListen {
    @Resource
    ApiLogsService apiLogsService;



    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "system.apilog.queue"),
            exchange = @Exchange(name = "system.apilog.exchange", type = ExchangeTypes.DIRECT),
            key = {"apilogcontroller", "apilog"}
    ))
    public void listenSystemLogsDirectQueue(ApiLogs apiLogs) {
//        System.out.println("消费者1接收到direct.queue1的消息：【" + apiLogs + "】");
        apiLogs.setAddress("未知地区");
      /*  try {
            String location = this.getLocation(apiLogs.getIpAddress());
            apiLogs.setAddress(location);
        } catch (IOException e) {
            apiLogs.setAddress("未知地区");
        }*/

        boolean save = apiLogsService.save(apiLogs);
//        System.out.println(save);
    }

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "system.error.queue"),
            exchange = @Exchange(name = "system.error.exchange", type = ExchangeTypes.DIRECT),
            key = {"error", "errorlog"}
    ))
    public void listenSystemErrorMQDirectQueue(MessageListener error) {

    }



    /**
     * 获取ip信息
     */
    public String getLocation(String ipAddress) throws IOException {

        String apiUrl = "http://ip-api.com/json/" + ipAddress;
        URL url = new URL(apiUrl);
        try {
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            connection.disconnect();
            return response.toString();
        } catch (IOException e) {
            return "未知地区";
        }


    }
}
